package com.xr.core.system.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.xr.common.axios.AxiosEnum;
import com.xr.common.axios.AxiosResult;
import com.xr.core.system.common.base.Result;
import com.xr.core.system.common.enums.ResultEnum;
import com.xr.common.exception.MyCustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Objects;
import java.util.Set;

/**
 * 自定义全局异常处理器
 */
@Slf4j
@Primary
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 定义打印请求日志方法
     *
     * @param request
     * @param e
     */
    private void PrintLogOfRequest(HttpServletRequest request, Exception e) {
        if (null != request) {
            log.error("请求方法：{}，请求地址：{}，程序异常：{}", request.getMethod(), request.getRequestURL(), e);
        } else {
            log.error("程序异常：", e);
        }
    }

    /**
     * 拦截系统发生的未知异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    Result<Object> handleGlobalUnknownException(Exception e, HttpServletRequest request) {
        PrintLogOfRequest(request, e);
        Result<Object> res;
        if (e instanceof NotLoginException) {
            res = Result.res(ResultEnum.UNAUTHENTICATED);
        } else if (e instanceof NotRoleException) {
            res = Result.res(ResultEnum.NOT_ROLE);
        } else if (e instanceof NotPermissionException) {
            res = Result.res(ResultEnum.UNAUTHORIZED);
        } else {
            // 发生未知错误，统一返回 `服务器异常` 的反馈消息
            res = Result.res(ResultEnum.ERROR, "服务器异常");
        }
        e.printStackTrace();
        return res;
    }

    /**
     * 拦截抛出的业务异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    Result<Object> handle(ServiceException e, HttpServletRequest request) {
        PrintLogOfRequest(request, e);
        ResultEnum code = e.getCode();
        String message = e.getMessage();
        if (null != code) {
            return Result.res(code, message);
        }
        return Result.error(message);
    }

    /**
     * 拦截不合法声明异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    Result<Object> handle(Exception e, HttpServletRequest request) {
        PrintLogOfRequest(request, e);
        return Result.res(ResultEnum.PARAMETER_ERROR, e.getMessage());
    }

    /**
     * 拦截缺少参数异常
     *
     * @param ex
     * @param request
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<Object> handle(MissingServletRequestParameterException ex, HttpServletRequest request) {
        PrintLogOfRequest(request, ex);
        return Result.res(ResultEnum.PARAMETER_ERROR, "缺少必要参数，参数名称为" + ex.getParameterName());
    }

    /**
     * 拦截controller方法参数上直接添加校验注解产生的的异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Object> handle(ConstraintViolationException e, HttpServletRequest request) {
        PrintLogOfRequest(request, e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String message = violation.getMessage();
        log.error(message);
        return Result.res(ResultEnum.PARAMETER_ERROR, message);
    }

    /**
     * 拦截get请求参数校验抛出的异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result<Object> handle(BindException e, HttpServletRequest request) {
        PrintLogOfRequest(request, e);
        // 获取异常中随机一个异常信息
        String defaultMessage = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.error(defaultMessage);
        return Result.res(ResultEnum.PARAMETER_ERROR, defaultMessage);
    }

    /**
     * 拦截处理请求参数格式错误产生的异常 （@RequestBody加上validate失败后抛出的异常是MethodArgumentNotValidException异常）
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handle(MethodArgumentNotValidException e, HttpServletRequest request) {
        PrintLogOfRequest(request, e);
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.error(message);
        return Result.res(ResultEnum.PARAMETER_ERROR, message);
    }

    /**
     * 拦截参数类型转换错误产生的异常
     *
     * @param exception
     * @param request
     * @return
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    public Result<Object> handle(HttpMessageConversionException exception, HttpServletRequest request) {
        PrintLogOfRequest(request, exception);
        log.error(exception.getCause().getLocalizedMessage());
        return Result.res(ResultEnum.PARAMETER_ERROR);
    }

    /**
     * 拦截字段值重复(违背unique约束条件)无法完成新增操作所抛出的SQL异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public AxiosResult handle(SQLIntegrityConstraintViolationException e) {
        e.printStackTrace();
        if (e.getMessage().contains("Duplicate entry")) {
            return AxiosResult.error(AxiosEnum.UNIQUE_ERROR);
        }
        return AxiosResult.error(AxiosEnum.UNKNOWN_ERROR);
    }

    /**
     * 拦截空指针异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    public AxiosResult handle(NullPointerException e) {
        e.printStackTrace();
        return AxiosResult.error(AxiosEnum.NULL_POINTER_ERROR);
    }

    /**
     * 拦截运行时发生的或主动抛出的其他自定义异常（继承于RuntimeException）
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MyCustomException.class)
    public AxiosResult handle(MyCustomException e) {
        e.printStackTrace();
        return AxiosResult.error(AxiosEnum.UNKNOWN_ERROR);
    }

}
